package com.song.tools.core.beans.response;

import com.song.tools.core.beans.LogId;
import com.song.tools.core.exception.ExceptionCodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * <p>
 * 通用响应结果vo
 * </p>
 *
 * @author song tools
 * @since 2024-06-06
 */
@Data
@Schema(title = "ResultVo", description = "通用响应结果")
@NoArgsConstructor
public class ResultVo<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = -5187628486516699925L;

    /**
     * 响应数据
     */
    @Schema(title = "data", description = "响应数据")
    private T data;

    /**
     * 响应编码
     */
    @Schema(title = "code", description = "响应编码", defaultValue = "0")
    private String code;

    /**
     * 响应信息，比如错误描述
     */
    @Schema(title = "message", description = "响应信息")
    private String message;

    /**
     * 日志ID
     */
    @Schema(title = "logId", description = "日志ID")
    private String logId;

    /**
     * 时间戳
     */
    @Schema(title = "timestamp", description = "时间戳")
    private Long timestamp;

    public ResultVo(T data, String code, String message) {
        this.data = data;
        this.code = code;
        this.message = message;
        this.timestamp = System.currentTimeMillis();
        this.logId = LogId.get();
    }

    public static ResultVo<Boolean> success() {
        return new ResultVo<>(Boolean.TRUE, ExceptionCodeEnum.SUCCESS.getCode(), null);
    }

    public static <T> ResultVo<T> success(T data) {
        return new ResultVo<>(data, ExceptionCodeEnum.SUCCESS.getCode(), null);
    }

    public static ResultVo<Boolean> error(String errorCode, String message) {
        return new ResultVo<>(Boolean.FALSE, errorCode, message);
    }

    public static ResultVo<Boolean> error(ExceptionCodeEnum exceptionCodeEnum) {
        return new ResultVo<>(Boolean.FALSE, exceptionCodeEnum.getCode(), exceptionCodeEnum.getDesc());
    }

    public boolean isSuccess() {
        return ExceptionCodeEnum.SUCCESS.getCode().equals(this.code);
    }
}
